package com.su.sweet.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;

import java.time.LocalDateTime;

/**
 * 自动填充创建人和修改人拦截器
 */
@Component
public class AutoFillInterceptor implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getCurrentUserId();
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createUser", Long.class, userId);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateUser", Long.class, userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getCurrentUserId();
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updateUser", Long.class, userId);
    }

    private Long getCurrentUserId() {
        Context ctx = Context.current();
        if (ctx != null) {
            String userId = ctx.header("userId");
            if (userId != null) {
                return Long.valueOf(userId);
            }
        }
        return -1L; // 默认值，表示系统操作
    }
}